<script setup lang="ts">
import type {VbenFormProps} from '@vben/common-ui';

import type {VxeGridProps} from '#/adapter/vxe-table';
import type {JobForm} from '#/api/system/job/model';

import { TableSwitch } from '#/components/table';
import {Page, useVbenModal} from '@vben/common-ui';
import {getVxePopupContainer} from '@vben/utils';

import {Dropdown, Menu, MenuItem, Modal, Popconfirm, Space} from 'ant-design-vue';

import {useVbenVxeGrid, vxeCheckboxChecked} from '#/adapter/vxe-table';
import {jobExport, jobList, jobRemove} from '#/api/system/job';
import {commonDownloadExcel} from '#/utils/file/download';

import {columns, querySchema} from './data';
import jobModal from './job-modal.vue';
import taskDetailModal from "./task-detail-modal.vue";
import {roleChangeStatus} from "#/api/system/role";
import { getDictOptions } from "#/utils/dict";
import { DictEnum } from "@vben/constants";
import type {Role} from "#/api/system/role/model";

const jobGroupOptions = getDictOptions(DictEnum.SYS_JOB_GROUP);
const jobGroupSlot = ({ row }) => {
    const match = jobGroupOptions.find((item) => item.value === row.jobGroup);
    return match ? match.label : row.jobGroup; // 找到则显示 label，否则显示原值
};


const formOptions: VbenFormProps = {
    commonConfig: {
        labelWidth: 80,
        componentProps: {
            allowClear: true,
        },
    },
    schema: querySchema(),
    wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const gridOptions: VxeGridProps = {
    checkboxConfig: {
        // 高亮
        highlight: true,
        // 翻页时保留选中状态
        reserve: true,
        // 点击行选中
        // trigger: 'row',
    },
    // 需要使用i18n注意这里要改成getter形式 否则切换语言不会刷新
    // columns: columns(),
    columns,
    height: 'auto',
    keepSource: true,
    pagerConfig: {},
    proxyConfig: {
        ajax: {
            query: async ({page}, formValues = {}) => {
                return await jobList({
                    pageNum: page.currentPage,
                    pageSize: page.pageSize,
                    ...formValues,
                });
            },
        },
    },
    rowConfig: {
        keyField: 'jobId',
    },
    // 表格全局唯一表示 保存列配置需要用到
    id: 'system-job-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
    formOptions,
    gridOptions,
});

const [JobModal, modalApi] = useVbenModal({
    connectedComponent: jobModal,
});

const [TaskDetailModal, monitorJob] = useVbenModal({
    connectedComponent: taskDetailModal,
});

function handleAdd() {
    modalApi.setData({});
    modalApi.open();
}

async function handleEdit(row: Required<JobForm>) {
    modalApi.setData({id: row.jobId});
    modalApi.open();
}

async function handleDelete(row: Required<JobForm>) {
    await jobRemove(row.jobId);
    await tableApi.query();
}

function handleMultiDelete() {
    const rows = tableApi.grid.getCheckboxRecords();
    const ids = rows.map((row: Required<JobForm>) => row.jobId);
    Modal.confirm({
        title: '提示',
        okType: 'danger',
        content: `确认删除选中的${ids.length}条记录吗？`,
        onOk: async () => {
            await jobRemove(ids);
            await tableApi.query();
        },
    });
}

function handleDownloadExcel() {
    commonDownloadExcel(
        jobExport,
        '定时任务调度数据',
        tableApi.formApi.form.values,
        {
            fieldMappingTime: formOptions.fieldMappingTime,
        },
    );
}
//  执行一次
function carryOut(record: Role) {
    console.log(record,'==1=====')
}

// 任务详细
function taskDetail(record: Role) {
    monitorJob.setData({ id: record.jobId });
    monitorJob.open();
}
// 调度日志
function schedulingLog() {

}

// // 定义弹框数据
// const [ExpressionModal, expressionModalApi] = useVbenModal({
//     fullscreenButton: false,
//     showDefaultActions: false,  // 如果不需要默认操作按钮
// });
//
// const showExpressionModal = ref(false);
//
// const handleGenerateExpression = () => {
//     showExpressionModal.value = true;  // 点击时打开表达式弹框
// };


</script>

<template>
    <Page :auto-content-height="true">
        <BasicTable table-title="定时任务调度列表">
            <template #toolbar-tools>
                <Space>
                    <a-button
                        v-access:code="['system:job:export']"
                        @click="handleDownloadExcel"
                    >
                        {{ $t('pages.common.export') }}
                    </a-button>
                    <a-button
                        :disabled="!vxeCheckboxChecked(tableApi)"
                        danger
                        type="primary"
                        v-access:code="['system:job:remove']"
                        @click="handleMultiDelete"
                    >
                        {{ $t('pages.common.delete') }}
                    </a-button>
                    <a-button
                        type="primary"
                        v-access:code="['system:job:add']"
                        @click="handleAdd"
                    >
                        {{ $t('pages.common.add') }}
                    </a-button>
                </Space>
            </template>
            <template #status="{ row }">
                <TableSwitch
                    v-model="row.status"
                    :api="() => roleChangeStatus(row)"
                    :disabled=" row.roleId === 1 ||  row.roleKey === 'admin'"
                    :reload="() => tableApi.query()"
                />
            </template>
            <template #jobGroup="{ row }">
                <div>{{ jobGroupSlot({ row }) }}</div>
            </template>
            <template #action="{ row }">
                <Space>
                    <ghost-button
                        v-access:code="['system:job:edit']"
                        @click.stop="handleEdit(row)"
                    >
                        {{ $t('pages.common.edit') }}
                    </ghost-button>
                    <Popconfirm
                        :get-popup-container="getVxePopupContainer"
                        placement="left"
                        title="确认删除？"
                        @confirm="handleDelete(row)"
                    >
                        <ghost-button
                            danger
                            v-access:code="['system:job:remove']"
                            @click.stop=""
                        >
                            {{ $t('pages.common.delete') }}
                        </ghost-button>
                    </Popconfirm>
                </Space>
                <Dropdown
                    :get-popup-container="getVxePopupContainer"
                    placement="bottomRight"
                >
                    <template #overlay>
                        <Menu>
                            <MenuItem key="1" @click="carryOut(row)">
                                执行一次
                            </MenuItem>
                            <MenuItem key="2" @click="taskDetail(row)">
                                任务详细
                            </MenuItem>
                            <MenuItem key="3" @click="schedulingLog">
                                调度日志
                            </MenuItem>
                        </Menu>
                    </template>
                    <a-button size="small" type="link">
                        {{ $t('pages.common.more') }}
                    </a-button>
                </Dropdown>
            </template>
        </BasicTable>
        <JobModal @reload="tableApi.query()"/>
        <!-- 任务详细弹框 -->
        <TaskDetailModal @reload="monitorJob.query()" />
    </Page>
</template>
